<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\MAdmin;
use App\Models\MAdminOperaLog;
use App\Models\MRoles;
use App\Utils\MenuUtil;
use Illuminate\Http\Request;


/**
 * 首页控制器
 */
class IndexController extends Controller
{

    /**
     * 获取后台验证码
     */
    public function yzm()
    {
        $img = captcha_src();
        if ($img) {
            $this->data = $this->makeJsCode(0, '验证码获取成功！');
            $this->data['img'] = $img;
        } else {
            $this->data = $this->makeJsCode(1, '验证码获取失败！');
        }

        return $this->apiJson($this->data);
    }

    /**
     * 管理员登录验证
     */
    public function loginAct(Request $request)
    {
        if (!$this->validateReq($request, MAdmin::loginRulesWithMsg(0), MAdmin::loginRulesWithMsg(1))) {
            $this->data = $this->makeJsCode(1, $this->errors->first());
            return $this->apiJson();
        }

        if ($admin = MAdmin::loginValid($request)) {
            $role = MRoles::find($admin->role_id);
            if ($role && $admin->loginStatus($role)->refreshIP($request->getClientIp())) {
                MAdminOperaLog::log($admin->id, $request->getClientIp(), '后台登录', "管理员[id:{$admin->id},name:{$admin->name}]登录后台");
                $this->data = $this->makeJsCode(0, '登录成功！');
                return $this->apiJson();
            } else {
                $this->data = $this->makeJsCode(1, '失败，请稍后再试！');
                return $this->apiJson();
            }
        } else {
            $this->data = $this->makeJsCode(1, '账号或密码错误！');
            return $this->apiJson();
        }

    }

    /**
     * 后台菜单栏控制器
     */
    public function adminMenu(Request $request)
    {
        $adminMenu = MenuUtil::adminMenu();
        $this->data = $this->makeJsCode(0, '请求成功！');
        $this->data['adminMenu'] = $adminMenu;
        return $this->apiJson();
    }


}